﻿using System;
using System.IO;
using System.Xml;
using System.Linq;
using System.Collections.Generic;
using Infrastructure.Serialization;

namespace PasswordControl.Core.Data
{
    public static class PackageProvider
    {
        private static ISerializer s_serializer = new Serializer();

        public static IPasswordPackage CreatePackage()
        {
            return new PasswordPackage();
        }

        public static IPasswordPackage GetPackage(string path, string password)
        {
            string encryptedData;
            using (var sr = new StreamReader(path))
            {
                encryptedData = sr.ReadToEnd();
            }
            string decryptedData = Encryption.Encryption.Decrypt(encryptedData, password);
            var xDoc = new XmlDocument();
            xDoc.LoadXml(decryptedData);
            return s_serializer.Deserialize<PasswordPackage>(xDoc.SelectSingleNode("*"));
        }

        public static void StorePackage(string path, string password, IPasswordPackage package)
        {
            var xDoc = new XmlDocument();
            s_serializer.Serialize(package, xDoc);
            string serializedData = xDoc.OuterXml;
            var encryptedData = Encryption.Encryption.Encrypt(serializedData, password);
            using (var sw = new StreamWriter(path))
            {
                sw.Write(encryptedData);
            }
        }
    }
}
